package com.raychi.demo.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import com.raychi.demo.entity.Company;
import com.raychi.demo.util.CompanyUtil;

public class CompanyDao {

	public List<Company> getCompanyList(Connection conn) throws ClassNotFoundException, SQLException {
		List<Company> companies = new ArrayList<Company>();
		Statement st = conn.createStatement();
		ResultSet rs = st.executeQuery("select * from company");
		Company company = null;
		while(rs.next()){
			company = CompanyUtil.createCompany(rs);
			companies.add(company);
		}
		return companies;
	}
	
	public void delete(Company company, Connection conn) throws Exception{
		Statement st = conn.createStatement();
		String sql = "delete from company where id="+company.getId();
		st.execute(sql);
	}
	
	public void save(Company company, Connection conn) throws Exception{
		String sql = "insert into Company (name, orderCount) values (?,?)";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setString(1, company.getName());
		ps.setInt(2, company.getOrderCount());
		ps.execute();
	}
	
	public  void  update(Company company,Connection conn) throws Exception{
		String sql = "update company set name = ?, orderCount = ? where id =" + company.getId();
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setString(1, company.getName());
		ps.setInt(2, company.getOrderCount());
		ps.executeUpdate();
	}
	
}
